package gherkinedit.wizard;

import gherkinedit.templatesystem.Template;

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;

public class InsertFromTemplateWizard extends Wizard {

	protected InsertFromTemplateWizardPage1 page1;
	protected InsertFromTemplateWizardPage2 page2;

	public InsertFromTemplateWizard() {
		super();
		setNeedsProgressMonitor(true);
	}

	@Override
	public void addPages() {
		page1 = new InsertFromTemplateWizardPage1(this);
		page2 = new InsertFromTemplateWizardPage2(this);
		addPage(page1);
		addPage(page2);
	}

	public Template getChoosenTemplate() {
		return page1.choosenTemplate;
	}

	@Override
	public boolean performFinish() {
		try {
			IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
			if (part instanceof ITextEditor) {
				final ITextEditor editor = (ITextEditor) part;
				IDocumentProvider prov = editor.getDocumentProvider();
				IDocument doc = prov.getDocument(editor.getEditorInput());
				ISelection sel = editor.getSelectionProvider().getSelection();
				if (sel instanceof TextSelection) {
					final TextSelection textSel = (TextSelection) sel;
					doc.replace(textSel.getOffset(), textSel.getLength(), page2.getTemplateResult());
				}
			}
		} catch (BadLocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}

	public void drawPage2() {
		page2.drawControls();
	}
}